package com.lance.answer.gui.answer.gk.video.tmp;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.video.dto.WatchVideoDto;
import com.lance.answer.section_import.SectionImport;
import com.lance.answer.util.CollectionsUtil;
import com.lance.answer.util.MD5Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WatchAllChapterTasktmp extends Thread {

    private final String driverPath;
    private final LinkedBlockingDeque<WatchVideoDto> watchVideos;

    public WatchAllChapterTasktmp(String driverPath, LinkedBlockingDeque<WatchVideoDto> watchVideos) {
        this.driverPath = driverPath;
        this.watchVideos = watchVideos;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchVideos.size() > 0) {
            WatchVideoDto watchVideo = watchVideos.take();
            String userName = watchVideo.getUserName();
            String password = watchVideo.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchVideos.size(), userName, password);
            System.err.println("执行任务11111");
            run(driverPath, watchVideo);
        }

        if (watchVideos.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void run(String driverPath, WatchVideoDto watchVideo) throws Exception {

        String subjectName = watchVideo.getSubjectName();
        String userName = watchVideo.getUserName();
        String password = watchVideo.getPassword();
        String JS = watchVideo.getJS();

        ChromeDriver driver = Util.getDriver(driverPath);
        try {
            String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
            driver.get(url);
            Thread.sleep(6000);
            Util.login(driver, userName, password);
            //Util.switchToLast(driver);
            Thread.sleep(6000);
            // 形考作业的链接 管理学

            boolean isFind = false;
            for (WebElement we : driver.findElements(By.className("media-body"))) {
                String mediaTitle = we.findElement(By.className("media-title")).getText();
                if (!mediaTitle.equals(subjectName)) {
                    continue;
                }
                //点击进入学习的按钮
                WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                studyButton.click();
                isFind = true;
                //Util.switchToLast(driver);
                Thread.sleep(6000);
            }


            // TODO 在这里统计有多少个视频已经刷了
            Util.switchToLast(driver);


            Thread.sleep(4000);


            InputStream answerInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + subjectName + "-answer.json");
            String answerStr = IOUtils.toString(answerInputStream,"UTF-8");
            List<AnswerObject> list = JSONObject.parseArray(answerStr, AnswerObject.class);
            Map<String, AnswerObject> answers = new HashMap<>();
            Map<String, AnswerObject> originAnswers = new HashMap<>();
            for (AnswerObject answerObject : list) {
                answers.put(answerObject.getQuestionCode(), answerObject);
                originAnswers.put(DealJsonString.saveZhWord(answerObject.getQuestionTitle()),answerObject);
            }

            for (String urlTask : getAllUrl(driver, userName)) {
                driver.get(urlTask);
                if(userName.equals("1951001460872")||userName.equals("2035001405205")){
                    Thread.sleep(10000);
                }
                Thread.sleep(2000);
                //  创建话题
                // div id='intro'

                if(urlTask.contains("quiz")){
                    // 答题
//                    if(Util.getVip().contains(userName)){
//                        doAnswer(driver,subjectName,answers,originAnswers);
//                    }
                   try {
                       doAnswer(driver,subjectName,answers,originAnswers);
                   }catch (Exception e){

                   }
                    continue;
                }

                if (urlTask.contains("forum")) {
                    // 获取页面的提示内容
                    try {
                        String content = driver.findElement(By.id("intro")).getText();
                        content = content.trim();
                        content = DealJsonString.removeSpace(content);
                        createTopic(driver, content.substring(0, content.length() > 20 ? 20 : content.length() / 2), content);
                    } catch (Exception e) {

                    }
                    Thread.sleep(5000);
                    continue;
                }


                if (driver.findElements(By.tagName("canvas")).size() > 0) {
                    // TODO 还没加入刷视频
                    try {
                        watchVideo(driver, JS);
                    //    watchVideo2(driver);
                    } catch (Exception e) {

                    }
                } else {
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,100)");
                    Thread.sleep(1000);
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,200)");
                    Thread.sleep(1000);
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,300)");
                    Thread.sleep(1000);
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,400)");
                    Thread.sleep(1000);
                    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,500)");
                    Thread.sleep(6000);
                }

            }


            //System.out.println(urlTasks.toString());
        } catch (Exception e) {
            e.printStackTrace();
            Thread.sleep(2000);
        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e) {

            }
        }
    }

    public static void doAnswer(WebDriver driver,String subjectName, Map<String, AnswerObject> answers , Map<String, AnswerObject> originAnswers) throws InterruptedException {

        try {
            List<WebElement> tdList = driver.findElements(By.cssSelector("td[class='cell c2']"));

            for (WebElement td : tdList) {
                String score = td.getText();
                //     System.err.println(score);
                if ("还未评分".equals(score)) {
                    System.err.println("还未评分");
                    return;
                }
            }
            // feedback

            String scoreString = driver.findElement(By.id("feedback")).getText();
            if(!Strings.isNullOrEmpty(scoreString)){
                return;
            }
        } catch (Exception e) {

        }




        try {
            Thread.sleep(5000);
            WebElement doWorkArea = driver.findElement(By.cssSelector("div[class='box py-3 quizattempt']"));
            doWorkArea.findElement(By.cssSelector("button[class='btn btn-secondary']")).click();
            Thread.sleep(2 * 1000);
            //回到试题首页
            WebElement element = driver.findElement(By.id("quiznavbutton1"));
            element.click();
            Thread.sleep(2 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // 回到首页
        //Util.goHomePageIndex(driver);
        boolean hashNextPage = true;
        while (hashNextPage) {
            try {
                Thread.sleep(4000);
                // 单个页面的所有题目的集合
                List<WebElement> singlePageQuestion = Util.getSinglePageQuestionList(driver);
                // 遍历每个问题|题目


                for (WebElement singleSubject : singlePageQuestion) {

                    WebElement contentElement = singleSubject.findElement(By.className("content"));

                    String title;
                    title = Util.getTitle(contentElement);
                    //兼容特殊字符
                    title = Util.dealContent(title);

                    String questionCode = MD5Utils.encode(subjectName + title);

                    // System.err.println("title:"+title);
                    AnswerObject answerObject ;
                    if(answers.containsKey(questionCode)){
                        answerObject=  answers.get(questionCode);
                    }else if(originAnswers.containsKey(DealJsonString.saveZhWord(title))){
                        answerObject=  originAnswers.get(DealJsonString.saveZhWord(title));
                    }else {
                        System.out.println("答案不存在");
                        System.out.println(title);
                        Map<String, String> map = new HashMap<>();
                        map.put("答案不存在", "未能从题库中匹配到");
                        map.put("答案标题", title);
                        map.put("课程名", subjectName);
                        //  Thread.sleep(5000000);
                        continue;
                    }

                    WebElement answerElement = Util.findByClassName(contentElement, "answer");
                    if (null != answerElement) {
                        // 开始答题
                        Util.doExercise(driver, answerElement, answerObject.getQuestionType(), answerObject.getAnswers());
                    } else {
                        // 如果为空就是填空题 是没有答案对比的
                        // 10-23 加了一个文件上传
                        Util.doExercise(driver, singleSubject, answerObject.getQuestionType(), answerObject.getAnswers());
                    }
                    //休眠一秒
                    TimeUnit.SECONDS.sleep(1);
                    //  FIXME 此时答案是没有保存的，要点击结束试答题
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Thread.sleep(2000);
                // FIX ME 获取当前页面的下一页信息 设置为while还是有下一页就继续循环
                WebElement nextPage = Util.findNextPage(driver);
                if (nextPage != null) {
                    nextPage.click();
                } else {
                    hashNextPage = false;
                    // FIXME  此时答案是没有保存的，要点击结束试答题 当没有下一页的时候，可以选择提交
                }
            }
        }


        Thread.sleep(2000);


        WebElement submitbtns = driver.findElement(By.className("submitbtns"));
        WebElement next = submitbtns.findElement(By.cssSelector("input[name='next']"));
        next.click();
        Thread.sleep(2000);


        //提交答案
        List<WebElement> saveButtons = driver.findElements(By.cssSelector("button[type='submit']"));
        //System.out.println("提交");
        //System.out.println(saveButtons.size());
        if (!CollectionUtils.isEmpty(saveButtons)) {
            for (WebElement webElement : saveButtons) {
                String text = webElement.getText();
                if (text.contains("提交")) {
                    webElement.click();
                }
            }
        }

        TimeUnit.SECONDS.sleep(3);
        //全部提交
        //提交答案



        List<WebElement> confirmation = driver.findElements(By.className("confirmation-dialogue"));
        if (!CollectionUtils.isEmpty(confirmation)) {
            for (WebElement webElement : confirmation) {
                List<WebElement> submitElement = webElement.findElements(By.tagName("input"));
                if (!CollectionUtils.isEmpty(submitElement)) {
                    for (WebElement element1 : submitElement) {
                        String value = element1.getAttribute("value");
                        if (value.contains("提交")) {
                            //点击确认后页面会刷新,此时为了防止丢到元素抛异常，这里直接获取第一个，不再循环
                            element1.click();
                            break;
                        }

                    }
                }
            }
        }


        List<WebElement> submitButtons = driver.findElements(By.tagName("input"));
        if (!CollectionUtils.isEmpty(submitButtons)) {
            for (WebElement webElement : submitButtons) {
                String text = webElement.getText();
                if (text.contains("提交")) {
                    webElement.click();
                }
            }
        }


    }


    public static void createTopic(WebDriver driver, String title, String answer) {
        try {
            WebElement doWorkArea = driver.findElement(By.cssSelector("*[class='btn btn-primary']"));
            doWorkArea.click();

            try {
                WebElement my = driver.findElement(By.cssSelector("span[class='usertext mr-1']"));
                title = title + "-" + my.getText();
            } catch (Exception e) {

            }
            driver.findElement(By.id("id_subject")).sendKeys(title);
            Thread.sleep(2000);
            WebElement iframe = driver.findElement(By.id("id_message_ifr"));
            String js = "document.getElementById('" + iframe.getAttribute("id") + "').contentWindow.document.body.innerText = '" + answer + "'";
            System.err.println(js);
            ((JavascriptExecutor) driver).executeScript(js);
            //  Thread.sleep(200000);
            driver.findElement(By.id("id_submitbutton")).click();
        } catch (Exception e) {
        }
    }

    // static void watchVideo(WebDriver driver,String urlTask)throws Exception{
    public static void watchVideo(WebDriver driver, String JS) throws Exception {

        System.err.println("开始观看视频！！！！！！！！！");
        //    Util.switchToFirst(driver);
        // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
        //  activityinstance.click();

        //延长加载时间
        Thread.sleep(5 * 1000);
        // Util.switchToUrl(driver,urlTask);
        Util.switchToLast(driver);
        Thread.sleep(2 * 1000);
        ((JavascriptExecutor) driver).executeScript(JS);
        Thread.sleep(2 * 1000);
        List<WebElement> canvas = driver.findElements(By.tagName("canvas"));
        //System.out.println("canvas大小");
        //System.out.println(canvas.size());
        for (WebElement player : canvas) {
            //System.out.println("class是：" + player.getAttribute("class"));
            if (player.getAttribute("class").startsWith("play")) {
                //System.out.println("找到啦 ");
                //System.out.println(player);
                player.click();
            } else {
                continue;
            }
        }

        //   Thread.sleep(18000);
        Thread.sleep(18000);
        //FIXME    driver.navigate().back();
        //   driver.get("http://xinjiang.ouchn.cn/course/view.php?id=1967");
    }

    public static void watchVideo2(WebDriver driver) throws Exception {

        System.err.println("开始观看视频！！！！！！！！！");

        //延长加载时间
        Thread.sleep(5 * 1000);

        List<WebElement> canvas = driver.findElements(By.tagName("canvas"));
        //System.out.println("canvas大小");
        //System.out.println(canvas.size());
        for (WebElement player : canvas) {
            //System.out.println("class是：" + player.getAttribute("class"));
            if (player.getAttribute("class").startsWith("play")) {
                //System.out.println("找到啦 ");
                //System.out.println(player);
                player.click();
            } else {
                continue;
            }
        }

        //   Thread.sleep(18000);
        Thread.sleep(5000);
        //FIXME    driver.navigate().back();
        //   driver.get("http://xinjiang.ouchn.cn/course/view.php?id=1967");
    }


    public static List<String> getAllUrl(WebDriver driver, String userName) {
        Set<Cookie> cookies = driver.manage().getCookies();
        String token = "";
        for (Cookie c : cookies) {
            if ("MoodleSession".equals(c.getName())) {
                token = c.getValue();
            }
        }
        System.err.println("token:" + token);
//

        Document doc = SectionImport.getDocument(driver.getCurrentUrl(), userName, token);
        Elements courses = doc.getElementsByClass("course-content");
//System.out.println(courses.toString());

        if (CollectionsUtil.isEmpty(courses)) {
            System.out.println("为空");
            return Lists.newArrayList();
        }
        Element course = courses.get(0);
        int sectionCount = 500;
        List<String> lines = new ArrayList<>();
        for (int i = 2; i <= sectionCount; i++) {
            Element section = course.getElementById("section-" + i);
            //System.out.println(section.toString());
            if (null != section) {
                //     Elements instances = section.select("li[class='activity url modtype_url'],li[class^='activity page modtype_page']");
                Elements instances = section.select("li[class^='activity']");
                for (Element instance : instances) {

                    Element btnWe = instance.selectFirst("button[class='btn btn-link'],span[class='autocompletion']");

                    if (btnWe == null) {
                        continue;
                    }
                    // WebElement imgWe = Util.findByCssSelector(btnWe, "img[class^='icon']");
                    Element imgWe = btnWe.selectFirst("img[class^='icon']");
                    if (imgWe == null) {
                        continue;
                    }

                    String imgText = imgWe.attr("title");
                    System.err.println("imgText:" + imgText);
                    if (!Strings.isNullOrEmpty(imgText) && imgText.contains("已完成")) {
                        continue;
                    }
                  try{
                      String line = instance.selectFirst("a[class='aalink']").attr("href");
                      if (line.contains("resource")) {
                          continue;
                      }
                      lines.add(line);
                  }catch (Exception e){

                  }
                }
                System.out.println("\n");
                System.out.println("\n");
                System.out.println("-----------------------------------------");
            }
        }
        return lines;

    }


}
